<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/28
 * Time: 11:10
 */

namespace app\api\controller;

use think\Db;

class Ali extends Base
{
    protected $config = array(
        'app_id' => '2021001155657538',
        'ali_public' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjWUoGBrlWFT2yFK2My7p7mwzVC83FZECeoSlHZJ+wdszj63r2HRwcvW/EqZjFrn5Vy5jAF4Y0zMntgagX+EV07swqWcyozXxH0kZrcrfmYgTG5wo1aVCCzyzAYl3X25O/lfZxtSBQjC7c0E1yqj4nvYHm86tEbLuVDCC5Pui6Hgp35hUYfEd31pzXlGMQ8v9xDAjX0ibuPYeVVRUXTdJcRPUbH6hw4AGunuvyMiuukT0Nhf9Wm75vEdCWFW3ABolqOMVLmOI3oBsjqPAGyDph9y0gPqU8GKn6CLV+ZUbc/CTLbx/8S17mIQ4fkEUJLPowONmyliBVEhGimj3YBKddQIDAQAB',
        'public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiRffD4qB8sJLWT0J3AZpQyVyUoOdPxl8eqnHpKBhaZ2s/kYSSIwiCQon0T2BImybmG29lHU/8TuQX6OTanELDfFnQtzxq0hRhPg2WOm2xsrBT1D/bl8OqfZks3I6UZ6j8DTB/u4oVDuLS2P+N2HATev8IIk3G616WtvdWFn5zTzQWI5f8Z80tahTxwzUgFocloUFLLMWUxVv9e1UHFSBcv8lV8T4WyAfpViLroBEJDhX6B1fKNRfRNd7+jGjcOCrMnoYUhF9Rk9pSwMCReMiy8wYHkRPiPdRZnilK9m7tEt2lZPdSv6oYOa5h8CclDxACpLmwntjnC8oHAvtnq9iOQIDAQAB",
        'private_key' => 'MIIEowIBAAKCAQEAiRffD4qB8sJLWT0J3AZpQyVyUoOdPxl8eqnHpKBhaZ2s/kYSSIwiCQon0T2BImybmG29lHU/8TuQX6OTanELDfFnQtzxq0hRhPg2WOm2xsrBT1D/bl8OqfZks3I6UZ6j8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WekRX2Wbo3v8CgYARiKgE4pHrv5kQquiNN7hJfSbfSIV0wqtGF+1jmRTDDZxK28DW6AnKchPpXpAXeb05+gD9hGqzC00wdDP8di9NJwINu8vNVOdXQJ/wJESyZUMY3uB8t9BULnVyGY5zpPwhYNi3Y4OKwK14TaXGkf0BDHjtV3DtK2Di+hcMmWQJjQKBgAUlyTuwNEp6rVoIqZGyN66S2pwjCTP2xO2Tzea6QgFi47U5wd4PPdNPLgI9bZ55cK5z6SC5z3BjiHdp6e7EXGEtZWoO9doybwfPW/1d9WYoG4VnuJ7dWDvP5rzvf5JZRxbDPA21mqH/jLausxuJuJSFhfUFqV0mIsd+osWU43X8'
    );
    public $body;//描述
    public $subject;//描述
    public $total_amount;//金额
    public $out_trade_no;//订单号
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {

    }
    /**
     * @param $no
     * @param $money
     * @return string
     * 支付宝支付
     */
    public function getParam($no, $money, $body, $subject)
    {
//
        import('alipay.aop.AopClient', EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeAppPayRequest', EXTEND_PATH);

        try {
            $aop = new \AopClient;
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do?charset=utf-8";
            $aop->appId = $this->config['app_id'];
            $aop->rsaPrivateKey = $this->config['private_key'];
            $aop->format = "json";
            $aop->charset = "UTF-8";
            $aop->signType = "RSA2";
            $aop->alipayrsaPublicKey = $this->config['public_key'];
            $request = new \AlipayTradeAppPayRequest();
            $bizcontent = "{\"body\":\"" . $body . "\","
                . "\"subject\": \"" . $subject . "\","
                . "\"out_trade_no\": \"" . $no . "\","
                . "\"timeout_express\": \"30m\","
                . "\"total_amount\": \"" . $money . "\","
                . "\"product_code\":\"QUICK_MSECURITY_PAY\""
                . "}";
            $request->setNotifyUrl("http://app.panson.com/api/Ali/huidiao");
            $request->setBizContent($bizcontent);
            $response = $aop->sdkExecute($request);
//            return $response;
            $res['msg'] = $response;
            $res['status'] = 200;
            return $res;
//            return json_encode($res);
        } catch(\Exception $e) {
            $res['msg'] = 'error';
            $res['status'] = 0;
            return $res;
        }
    }
    
    /**
     * 验证返回
     * @return bool
     */
    public function checkReturn()
    {
        import('alipay.aop.AopClient', EXTEND_PATH);
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = $this->config['ali_public'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag) {
            return $_POST;
        } else {
            return false;
        }
    }
    /***
     * @param $code
     * @param string $msg
     * 错误返回信息
     */
    protected function apiError($code, $msg = '')
    {
        if (!$msg) {
            $info['msg'] = $this->_error[$code]['msg'];
        } else {
            $info['msg'] = $msg;
        }
        $info['status'] = $code;
        $returnInfo = json_encode($info, JSON_UNESCAPED_UNICODE);
        echo $returnInfo;
        exit();
    }

    
    /**
     * 回调
     * @return string
     */
    public function write_admin_log($data)
    {
        $file_name = 'file/log/' . date('Ymd', time()) . '.txt';
        if (is_array($data)) {
            $data_str = implode(' | ', $data);
        } else {
            $data_str = $data;
        }
        file_put_contents($file_name, $data_str . "\r\n\r\n", FILE_APPEND);
    }

    public function huidiao()
    {
        $getInfo = $this->checkReturn();
        if($getInfo) {
            if($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED') {
                $num = $getInfo['out_trade_no'];//订单号
                $back_order_id = $getInfo['trade_no']; // 订单号
                //统购付了再走
                $tg = Db::table('up_offline_tgorder')->where('orderno',$num)->field('id')->find();
                if($tg){
                    $tgres = Db::table('up_offline_tgorder')->where('orderno',$num)->update([
                        'status' => 2,
                        'backno' => $back_order_id,
                        'time' => date('Y-m-d H:i:s')
                    ]);
                    if($tgres){
                        $result = true;
                    }else{
                        $result = false;
                    }
                }else{
                    $result = $this->alltypespay($num,$back_order_id);
                }
                if($result == true){
                    return 'success';
                }else{
                    return 'error';
                }
            }
        }
    }


    /**
     *支付宝的原路退款接口(商户处理用户的订单)
     */
    public function refund($payInfo,$refundNo){
        //仨参数：money,number
        import('alipay.aop.AopClient',EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeRefundRequest',EXTEND_PATH);
        $aop = new \AopClient;
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $this->config['app_id'];
        $aop->rsaPrivateKey = $this->config['private_key'];
        $aop->alipayrsaPublicKey=$this->config['ali_public'];
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayTradeRefundRequest;
        $refundAmount = $payInfo['money'];
        $request->setBizContent("{" .
            "\"out_trade_no\":\"{$payInfo['number']}\"," .
            "\"refund_amount\":$refundAmount," .
            "\"refund_reason\":\"正常退款\"," .
            "\"out_request_no\":\"$refundNo\"," .
            "\"operator_id\":\"OP001\"," .
            "\"store_id\":\"NJ_S_001\"," .
            "\"terminal_id\":\"NJ_T_001\"" .
            "  }");
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        // dump($result);die;
        if(!empty($resultCode) && $resultCode == 10000){
            return array('status'=>200,'msg'=>'操作成功');
        }else{
            return array('status'=>0,'msg'=>'调用接口失败（余额不足或者超出实际支付金额）');
        }
    }
    /**
     * 查支付结果
     */
    public function chaxunPayAli($refundNo){
        import('alipay.aop.AopClient',EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeQueryRequest',EXTEND_PATH);
        $aop = new \AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $this->config['app_id'];
        $aop->rsaPrivateKey = $this->config['private_key'];
        $aop->alipayrsaPublicKey=$this->config['ali_public'];
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayTradeQueryRequest ();
        $request->setBizContent("{" .
            "  \"out_trade_no\":\"{$refundNo}\"," .
            "  \"query_options\":[" .
            "    \"trade_settle_info\"" .
            "  ]" .
            "}");
        $result = $aop->execute ( $request);
        $result = json_decode(json_encode($result),true);
        $code = $result['alipay_trade_query_response']['code'];
        if($code == 10000 && isset($result['alipay_trade_query_response']['trade_status'])){
            if($result['alipay_trade_query_response']['trade_status'] == 'TRADE_SUCCESS'){
                $result = $this->alltypespay($refundNo,$result['alipay_trade_query_response']['trade_no']);
                return $result;
            }
        }
        return false;
    }
}